package com.fans.admin.sys.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fans.admin.sys.dao.SysUserMapper;
import com.fans.admin.sys.entity.SysRole;
import com.fans.admin.sys.entity.SysUser;
import com.fans.admin.sys.entity.SysUserRole;
import com.fans.admin.sys.service.ISysRoleMenuService;
import com.fans.admin.sys.service.ISysUserRoleService;
import com.fans.admin.sys.service.ISysUserService;
import com.fans.admin.sys.vo.RoleMenuPerms;
import com.fans.common.constant.SysConstant;
import com.fans.common.redis.util.JedisUtils;
import com.fans.common.utils.BlankUtils;
import com.fans.common.utils.SecurityUtils;
import com.fans.common.utils.jwt.TokenUtil;

/**
 * @description: 系统_用户服务实现类
 * @date: 2019年12月19 17:17:39
 * @author: fanhaohao
 * @version: 1.0
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements ISysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private ISysUserRoleService sysUserRoleService;// 用户角色业务类
	
	@Autowired
	private ISysRoleMenuService sysRoleMenuService;

	/**
	 * @Title：list  
	 * @Description: 系统_用户分页查询
	 * @author: fanhaohao
	 * @date 2019年12月19 17:17:39
	 * @param @param page
	 * @param @param map
	 * @param @return 
	 * @return List<Map<String,Object>> 
	 * @throws
	 */
	@Override
	public List<Map<String, Object>> list(Page<SysUser> page,Map<String, Object> map){
		return sysUserMapper.list(page, map);
	}

	/**
	 * @Title：deleteBatchByIdLogic  
	 * @Description: 系统_用户根据id逻辑删除
	 * @author: fanhaohao
	 * @date 2019年12月27 10:31:34
	 * @param @param id 
	 * @return void 
	 * @throws
	 */
	@Override
	public void deleteBatchByIdLogic(Object id){
		SysUser sysUser = new SysUser();
		sysUser.setId(String.valueOf(id));
		sysUser.preUpdate();
		sysUser.setUpdateBy(TokenUtil.getUserId());
		sysUser.setDelFlag("1");
		this.updateById(sysUser);
	}
	
	/**
	 * @Title：deleteBatchByIdsLogic    
	 * @Description: 系统_用户逻辑批量删除
	 * @author: fanhaohao
	 * @date 2019年12月27 10:31:34
	 * @param @param ids 
	 * @return void 
	 * @throws
	 */
	@Override
	public void deleteBatchByIdsLogic(List<Object> ids) {
		List<SysUser> list = new ArrayList<>();
		for (Object id : ids) {
			SysUser sysUser = new SysUser();
			sysUser.setId(String.valueOf(id));
			sysUser.preUpdate();
			sysUser.setUpdateBy(TokenUtil.getUserId());
			sysUser.setDelFlag("1");
			list.add(sysUser);
		}
		this.updateBatchById(list);
	}
	
	/**
	 * @Title：updateLoginResult  
	 * @Description: 根据登录结果更新登录次数时间信息
	 * @author: fanhaohao
	 * @date 2019年12月20日 上午11:38:55 
	 * @param @param username
	 * @param @param bool 
	 * @return void 
	 * @throws
	 */
	@Override
	public void updateLoginResult(String username, Boolean bool) {
		sysUserMapper.updateLoginResult(username, bool);
	}

	/**
     * @Title：selectByUsername  
     * @Description: 根据名字来查询用户信息
     * @author: fanhaohao
     * @date 2019年12月20日 下午2:49:06 
     * @param @param username
     * @param @return 
     * @return SysUser 
     * @throws
     */
	@Override
	public SysUser selectByUsername(String username) {
		SysUser user = new SysUser();
		user.setUsername(username);
		return sysUserMapper.selectOne(user);
	}

	/**
	 * @Title：resetPwd  
	 * @Description: 重置用户密码
	 * @author: fanhaohao
	 * @date 2019年12月25日 下午3:53:48 
	 * @param @param id 
	 * @return void 
	 * @throws
	 */
	@Override
	public void resetPwd(String id) {
		SysUser user = new SysUser();
		user.setId(id);
		user.preUpdate();
		user.setUpdateBy(TokenUtil.getUserId());
		user.setPassword(SecurityUtils.MD5Encode(SysConstant.INIT_PWD));
		super.updateById(user);
	}
	
	/**
	 * @Title：updatePwd  
	 * @Description: 用户修改密码
	 * @author: fanhaohao
	 * @date 2019年12月25日 下午5:32:31 
	 * @param @param userId
	 * @param @param newpwd 
	 * @return void 
	 * @throws
	 */
	@Override
	public void updatePwd(String userId, String newpwd) {
		SysUser user = new SysUser();
		user.setId(userId);
		user.preUpdate();
		user.setUpdateBy(userId);
		user.setPassword(SecurityUtils.MD5Encode(newpwd));
		super.updateById(user);
	}

	/**
	 * @Title：saveUserInfo  
	 * @Description: 保存用户信息
	 * @author: fanhaohao
	 * @date 2019年12月26日 下午4:51:51 
	 * @param @param sysUser 
	 * @return void 
	 * @throws
	 */
	@Override
	public void saveUserInfo(SysUser sysUser) {
		this.insert(sysUser);
		String roleId = sysUser.getRoleId();
		if (BlankUtils.isNotBlank(roleId)) {// 如果角色id不为空进行用户角色表的添加操作
			List<SysUserRole> entityList = new ArrayList<>();
			String[] roleArr = roleId.split(";;");
			for (String ra : roleArr) {
				SysUserRole userRole = new SysUserRole();
				userRole.setRoleId(ra);
				userRole.setUserId(sysUser.getId());
				userRole.preInsert();
				userRole.setCreateBy(TokenUtil.getUserId());
				entityList.add(userRole);
			}
			sysUserRoleService.insertBatch(entityList);
		}
	}

	/**
	 * @Title：updateUserInfo  
	 * @Description: 更新用户信息
	 * @author: fanhaohao
	 * @date 2019年12月26日 下午4:53:13 
	 * @param @param sysUser 
	 * @return void 
	 * @throws
	 */
	@Override
	public void updateUserInfo(SysUser sysUser) {
		this.updateById(sysUser);
		String roleId = sysUser.getRoleId();
		List<String> roleIdList = sysUserRoleService.roleIdListByUserId(sysUser.getId());
		if (BlankUtils.isNotBlank(roleId)) {// 如果角色id不为空进行用户角色表的更新操作
			List<SysUserRole> insertEntityList = new ArrayList<>();
			String[] roleArr = roleId.split(";;");
			for (String ra : roleArr) {
				if (!roleIdList.contains(ra)) {
					SysUserRole userRole = new SysUserRole();
					userRole.setRoleId(ra);
					userRole.setUserId(sysUser.getId());
					userRole.preInsert();
					userRole.setCreateBy(TokenUtil.getUserId());
					insertEntityList.add(userRole);
				} else {
					roleIdList.remove(ra);
				}
			}
			if (BlankUtils.isNotBlank(insertEntityList)) {
				sysUserRoleService.insertBatch(insertEntityList);
			}
			if (BlankUtils.isNotBlank(roleIdList)) {
				sysUserRoleService.deleteBatchByRoleIds(roleIdList, sysUser.getId());
			}
		} else {
			if (BlankUtils.isNotBlank(roleIdList)) {
				sysUserRoleService.deleteBatchByRoleIds(roleIdList, sysUser.getId());
			}
		}
	}

	/**
	 * 根据username和password查询
	 * @param username
	 * @param password
	 * @return
	 */
	@Override
	public SysUser getByUsernameAndPassword(String username, String password) {
		SysUser user = new SysUser();
		user.setUsername(username);
		user.setPassword(SecurityUtils.MD5Encode(password));
		user = sysUserMapper.selectOne(user);
		return user;
	}
	
	/**
	 * 根据email和password查询
	 * @param email
	 * @param password
	 * @return
	 */
	@Override
	public SysUser getByEmailAndPassword(String email, String password) {
		SysUser user = new SysUser();
		user.setEmail(email);
		user.setPassword(SecurityUtils.MD5Encode(password));
		user = sysUserMapper.selectOne(user);
		return user;
	}
	
	/**
	 * 根据mobile和password查询
	 * @param mobile
	 * @param password
	 * @return
	 */
	@Override
	public SysUser getByMobileAndPassword(String mobile, String password) {
		SysUser user = new SysUser();
		user.setMobile(mobile);
		user.setPassword(SecurityUtils.MD5Encode(password));
		user = sysUserMapper.selectOne(user);
		return user;
	}
	
	/**
	 * @Title：getLoginDatas  
	 * @Description: 获取登录后的信息
	 * @author: fanhaohao
	 * @date 2020年01月20日 下午2:06:23 
	 * @param @param username
	 * @param @param password
	 * @param @param menuPerms
	 * @param @return 
	 * @return Map<String, Object> 
	 * @throws
	 */
	@Override
	public Map<String, Object> getLoginDatas(String username, boolean menuPerms) {
		SysUser sysUser = this.selectByUsername(username);
		// 返回信息
		Map<String, Object> rtDatas = new HashMap<>();
		// 用户信息
		Map<String, Object> userData = new HashMap<>();
		userData.put("userName", sysUser.getUsername());
		userData.put("id", sysUser.getId());
		// 获得角色和角色权限
		List<SysRole> sysRoleList = sysUserRoleService.listByUserId(sysUser.getId(), null);
		if (BlankUtils.isNotBlank(sysRoleList)) {
			int roleSize = sysRoleList.size();
			Set<String> roleIds = new HashSet<>(roleSize);
            List<String> roleNames = menuPerms ? new ArrayList<>(roleSize) : null;
            List<String> mains = menuPerms ? new ArrayList<>(roleSize) : null;
			for (SysRole r : sysRoleList) {
				if (BlankUtils.isNotBlank(r)) {
                    roleIds.add(r.getId());
                    if (menuPerms) {
                        roleNames.add(r.getName());
                        mains.add(r.getMain());
                    }
                }
            }
            // 是否获取菜单权限
            if (menuPerms) {
                userData.put("roleName", roleNames.toString());
                userData.put("main", mains.toString());
				RoleMenuPerms roleMenuPerms = sysRoleMenuService.getRoleMenuAndPerms(coverRoleIds(roleIds));
				rtDatas.put("menuData", roleMenuPerms.getMenuList());
				rtDatas.put("permsData", roleMenuPerms.getPermsList());
				// 登录后把按钮权限标识保存到redis缓存中
				JedisUtils.setObject(SysConstant.PERMS_MENU_DATA + sysUser.getId(), roleMenuPerms.getPermsList(), 0);
            }
        }
		rtDatas.put("userData", userData);
		this.updateLoginResult(sysUser.getUsername(), true);// 更新登录成功次数
		return rtDatas;
    }
	/**
	 * @Title：coverRoleIds  
	 * @Description: roleids 拼接成字符串 ‘id1’，‘id2’的格式
	 * @author: fanhaohao
	 * @date 2020年01月26日 下午5:40:00 
	 * @param @param roleIdsroleIds
	 * @param @return 
	 * @return String 
	 * @throws
	 */
	private String coverRoleIds(Set<String> roleIdsroleIds) {
		StringBuffer sb = new StringBuffer();
		for (String roleId : roleIdsroleIds) {
			sb.append("'").append(roleId).append("',");
		}
		String rt = sb.toString();
		if (rt.contains(",")) {
			rt = rt.substring(0, rt.lastIndexOf(","));
		}
		return rt;
	}

}
